#!/usr/bin/env bash

rkspace=$(pwd)
service=$2
port=$4
command=$1
INPUT_JAVA_OPTIONS=$6
memory=$5
profile=$3
if [ -z ${profile} ]
then
profile="dev"
fi
if [ -z ${memory} ]
then
memory="250M"
fi
if [ -z ${port} ]
then
port=""
else
port="-Dserver.port=$port"
fi
jarFile=$(find ${workspace} -name ${service}*.jar)
JAVA_OPTIONS="-Xmx$memory -Xms$memory -XX:MaxMetaspaceSize=150M -XX:-UseCompressedClassPointers -Dspring.profiles.active=$profile $port $INPUT_JAVA_OPTIONS"
echo ${command}


#检查服务进程
checkPid(){
echo $(echo $(ps -ef | grep ${service} | grep java | awk '{print $2}'))
}

##启动程序
startApp(){
echo "starting"
echo $2
nohup java $2 -jar $1 /dev/null 2>&1 &
echo "start $1 success options $2"
for i in {1..60}
    do
      local pid=$(checkPid)
     if [ -z ${pid} ]
     then
       if [ ${i} -eq 60 ]
       then
         echo "start $1 options $2 fail start success pid unchecked"
         break
       else
         echo "check pid $pid fail $i"
         sleep 1s
       fi
     else
       echo "$1 started pid $pid"
       break;
     fi
    done
}

#停止程序
stopApp(){
  echo "stopping"

  local pid=$(checkPid)
  echo "$pid"
  if [ -z ${pid} ]
  then
    echo "no started app"
  else
    kill ${pid}
    echo "stop $1 pid: $pid"

  for i in {1..60}
      do
        local check=$(checkPid)
        if [ -z ${check} ]
        then
          echo "stop $1 pid $pid success"
          break
        else
          if [ ${i} -eq 60 ]
          then
           echo "stop pid $pid fail kill -9 $1"
           kill -9 pid
          fi
          sleep 1s
          echo "stopping $1 pid $pid waiting ${i}s"
        fi
      done
  fi
}

if [[ ${command} = "start" ]]
then
 startApp ${jarFile} "${JAVA_OPTIONS}"
elif [[ ${command} = "stop" ]]
then
 stopApp ${service}
elif [[  ${command} = "restart" ]]
then
 stopApp ${service}
 startApp ${jarFile} "${JAVA_OPTIONS}"
else
 echo "no support command $command"
fi

